package controllers

import (
	"marx/models"

	"time"

	"strconv"

	"github.com/astaxie/beego"
)

type SearchController struct {
	beego.Controller
}

func (this *SearchController) Get() {
	this.TplName = "search.html"
}

// 查询航班信息
func (this *SearchController) Post() {
	source := this.Input().Get("source")
	destination := this.Input().Get("destination")
	//获取时间
	dateString := this.Input().Get("datum")
	var dateTime time.Time

	if dateString == "" {
		dateTime = time.Now()
	} else {
		var err error
		dateTime, err = models.String2Time(dateString)
		if err != nil {
			beego.Error(err)
			return
		}
	}
	alines, err := models.Search3(source, destination, dateTime)
	if err != nil {
		beego.Error(err)
		return
	}

	codejson := Message{Code: 0, Data: alines, Msg: "查询成功"}

	this.Data["json"] = codejson
	this.ServeJSON()

	this.Redirect("", 302)
	return

}

// 查询目的地点
func (this *SearchController) Getdest() {
	dest, status := models.Listdest()
	var codejson interface{}
	if status == 0 {
		codejson = Message{Code: 0, Data: dest, Msg: "查询目的地点成功"}
	} else {
		codejson = Message{Code: 1, Data: dest, Msg: "查询目的地点失败"}
	}
	this.Data["json"] = codejson
	this.ServeJSON()
	this.Redirect("", 302)
	return
}

// 查询出发地点
func (this *SearchController) Getsource() {
	dest, status := models.Listsource()
	var codejson interface{}
	if status == 0 {
		codejson = Message{Code: 0, Data: dest, Msg: "查询出发地点成功"}
	} else {
		codejson = Message{Code: 1, Data: dest, Msg: "查询出发地点失败"}
	}
	this.Data["json"] = codejson
	this.ServeJSON()
	this.Redirect("", 302)
	return
}

// 查询用户的订单信息
func (this *SearchController) Getorder() {
	name, _, flag := checkAccount(this.Ctx)
	var codejson interface{}
	if flag {
		// name := this.Ctx.GetCookie("name")
		orders, status := models.Getticket(name)
		if status == 0 {
			codejson = Message{Code: 0, Data: orders, Msg: "查询订单成功"}
		} else {
			codejson = Message{Code: 1, Data: nil, Msg: "系统错误"}
		}
	} else {
		codejson = Message{Code: 1, Data: nil, Msg: "尚未登录"}
	}
	this.Data["json"] = codejson
	this.ServeJSON()
	this.Redirect("", 302)
	return
}

func (this *SearchController) Getseat() {
	var codejson interface{}
	name, _, flag := checkAccount(this.Ctx)
	if flag {
		alineid := this.Input().Get("alineid")
		aid, err := strconv.ParseInt(alineid, 10, 64)
		if err != nil {
			codejson = Message{Code: 1, Data: nil, Msg: "航班信息错误"}
		} else {
			seat, status := models.Getseatmess(name, aid)
			if status == 0 {
				codejson = Message{Code: 0, Data: seat, Msg: "查询订单成功"}
			} else {
				codejson = Message{Code: 1, Data: nil, Msg: "系统错误"}
			}
		}

	} else {
		codejson = Message{Code: 1, Data: nil, Msg: "尚未登录"}
	}
	this.Data["json"] = codejson
	this.ServeJSON()
	this.Redirect("", 302)
	return
}
